package com.suitsoft.ut.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 压缩工具类.
 * 
 * @author ldy
 */
public class ZipFileUtils {
	/** 日志输出对象 */
	protected static final Logger logger = LoggerFactory.getLogger(ZipFileUtils.class);
	/** 缓冲区大小 */
	private static final int BUFFER_SIZE = 1024;
	
	private ZipFileUtils() {
	
	}
	
	/**
	 * @param orgPath 源文件路径
	 * @param desPath 保存路径
	 */
	public static boolean zip(String orgPath) {
		boolean result = false;
		
		FileInputStream fis = null;
		ZipOutputStream zos = null;

		File f = new File(orgPath);
		
		try {
			zos = new ZipOutputStream(new FileOutputStream(orgPath + ".zip"));
			//指定编码为gbk，否则部署到linux下会出现乱码
			zos.setEncoding("gbk");
			String name = f.getName();
			zos.putNextEntry(new ZipEntry(name));
			int len;
			byte[] buff = new byte[BUFFER_SIZE];

			fis = new FileInputStream(f);
			while ((len = fis.read(buff)) != -1) {
				zos.write(buff, 0, len);
			}
			
			zos.flush();
			result = true;
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			try {
				if (zos != null) {
					zos.close();
				}
				
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
			}
		}
		
		return result;
	}
}
